package lium.lbs.lbsim.chat

import android.Manifest
import android.content.Intent
import android.os.Bundle
import android.view.Gravity
import lium.lbs.lbsim.activity.BaseActivity
import com.tbruyelle.rxpermissions2.RxPermissions
import lium.lbs.lbsim.R
import lium.lbs.lbsim.utils.IAlertDialog
import android.os.Build
import android.os.Environment
import android.view.View
import com.cjt2325.cameralibrary.JCameraView
import com.lmlibrary.Constants
import lium.lbs.lbsim.utils.ToastUtils
import kotlinx.android.synthetic.main.msg_activity_record_video_layout.*
import android.graphics.Bitmap
import android.widget.Toast
import com.cjt2325.cameralibrary.listener.JCameraListener
import com.lzy.okgo.utils.OkLogger
import lium.lbs.lbsim.utils.BitmapUtils
import lium.lbs.lbsim.utils.SdcardUtils
import java.io.File

class RecordVideoActivity : BaseActivity() {
    override fun getLayoutId(): Int {
        return R.layout.msg_activity_record_video_layout
    }

    override fun initView(savedInstanceState: Bundle?) {
        requestPhotoPermissions()
    }

    // 相册
    private fun requestPhotoPermissions() {
        val rxPermission = RxPermissions(this)
        rxPermission.request(
            Manifest.permission.CAMERA,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_SETTINGS
        )
            .subscribe { granted ->
                if (granted!!) {
                    initCameraView()
                } else {
                    requestPerFailed(resources.getString(R.string.app_name) + "需要相机和对焦权限，请到设置开启权限允许")
                }
            }
    }

    override fun getNetWorkData() {
    }

    internal var dialog: IAlertDialog? = null
    fun requestPerFailed(msg: String) {
        dialog = IAlertDialog(this, IAlertDialog.LayoutStyle.THEME_WHITE_TITLE_SINGLEBUTTON, Gravity.CENTER)
        dialog!!.setMessage(msg)
        dialog!!.setPositiveMsg("确定")
        dialog!!.setPositiveOnClickListener { dialog, which ->
            finish()
        }
        dialog!!.show()
    }

    fun initCameraView() {
        //设置视频保存路径
        jcameraview.setSaveVideoPath(Environment.getExternalStorageDirectory().path + Constants.VOICE_CACHE_DIR)
        //设置只能录像或只能拍照或两种都可以（默认两种都可以）
        jcameraview.setFeatures(JCameraView.BUTTON_STATE_BOTH)
        //设置视频质量
        jcameraview.setMediaQuality(JCameraView.MEDIA_QUALITY_MIDDLE)
        jcameraview.setTip("长按录制视频")

        //JCameraView监听
        jcameraview.setErrorLisenter(object :  com.cjt2325.cameralibrary.listener.ErrorListener {
            override fun onError() {
                ToastUtils.showToast("相机不可用")
            }
            override fun AudioPermissionError() {
                requestPerFailed(resources.getString(R.string.app_name) + "需要相机和对焦权限，请到设置开启权限允许")
            }
        })
        val REQUEST_CODE_CAMERA = 1111 //拍摄
        val REQUEST_CODE_VEDIO = 2222 //录制
        jcameraview.setJCameraLisenter(object : JCameraListener {
            override fun captureSuccess(bitmap: Bitmap?) {
                //获取图片bitmap
                var filename = System.currentTimeMillis().toString()
                if (SdcardUtils.existSdcard()) {
                    SdcardUtils.saveBitmap2SD(bitmap, Constants.IMAGE_CACHE_DIR, filename + "")
                } else{
                    Toast.makeText(this@RecordVideoActivity, "拍摄失败，未检测到SD卡", Toast.LENGTH_SHORT).show()
                }
                BitmapUtils.recycleBitmap(bitmap)

                var imagefile = File(Environment.getExternalStorageDirectory().toString() + Constants.IMAGE_CACHE_DIR + "" + filename + ".jpg")
                OkLogger.e("图片是否存在："+imagefile.exists())

                setResult(REQUEST_CODE_CAMERA, Intent().putExtra("imagePath",imagefile.absolutePath))
                finish()
            }

            override fun recordSuccess(url: String?, firstFrame: Bitmap?) {
                var filename = System.currentTimeMillis().toString()
                if (SdcardUtils.existSdcard()) {
                    SdcardUtils.saveBitmap2SD(firstFrame, Constants.IMAGE_CACHE_DIR, filename + "")
                } else{
                    Toast.makeText(this@RecordVideoActivity, "录制失败，未检测到SD卡", Toast.LENGTH_SHORT).show()
                }
                BitmapUtils.recycleBitmap(firstFrame)

                var imagefile = File(Environment.getExternalStorageDirectory().toString() + Constants.IMAGE_CACHE_DIR + "" + filename + ".jpg")
                OkLogger.e("图片是否存在："+imagefile.exists())

                setResult(REQUEST_CODE_VEDIO, Intent().putExtra("thumbnailPath",imagefile.absolutePath).putExtra("recordPath",url))
                finish()
            }


        })
        //左边按钮点击事件
        jcameraview.setLeftClickListener { this@RecordVideoActivity.finish() }

        //右边按钮点击事件
        jcameraview.setRightClickListener {
            ToastUtils.showToast("右边按钮点击事件")
        }
    }


    override fun onResume() {
        super.onResume()
        jcameraview.onResume()
    }

    override fun onPause() {
        super.onPause()
        jcameraview.onPause()
    }
    override fun onStart() {
        super.onStart()
        //全屏显示
        if (Build.VERSION.SDK_INT >= 19) {
            val decorView = window.decorView
            decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    or View.SYSTEM_UI_FLAG_FULLSCREEN
                    or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)
        } else {
            val decorView = window.decorView
            val option = View.SYSTEM_UI_FLAG_FULLSCREEN
            decorView.systemUiVisibility = option
        }
    }

}
